<template>
  <view class="profile-container">
    <!-- 背景图片 -->
    <image class="background-image" src="/static/wode.png" mode="aspectFill"></image>

    <!-- 用户信息区域 -->
    <view class="user-info-section">
      <view class="user-avatar" @click="handleAvatarClick">
         <view class="user-avatar-kua">
			 <image
			   class="avatar-img"
			   :src="userInfo.avatar"
			   :key="userInfo.avatar"
			   mode="aspectFill"
			   @error="onAvatarError"
			   @load="onAvatarLoad"
			 ></image>
		 </view>
         <image v-if="isUserLoggedIn && userInfo.is_svip && userInfo.is_svip != 0" class="vip-crown" src="/static/index10.png" mode=""></image>
      </view>
      <view class="user-details">
        <view class="name-row">
          <text class="user-name">{{ userInfo.userName }}</text>
          <text class="user-id">{{ userInfo.userId }}</text>
        </view>
        <text class="user-bio">{{ userInfo.signature }}</text>
      </view>
    </view>
    
    <!-- 数据统计区域 -->
    <view class="stats-section">
      <view class="stat-card">
        <view class="stat-icon search-icon">
         <image class="icon-text" src="/static/index8.png" mode=""></image>
        </view>
         <view class="stat-label">
              <text class="stat-number">{{ userInfo.searchCount || 0 }}</text>
        <text class="stat-label">搜题次数</text>
         </view>
      </view>

      <view class="stat-card" @click="goToInviteFriendsRecord">
        <view class="stat-icon friends-icon">
            <image class="icon-text" src="/static/index9.png" mode=""></image>
        </view>
         <view class="stat-label">
              <text class="stat-number">{{ userInfo.friendCount || 0 }}</text>
        <text class="stat-label">好友人数</text>
         </view>
      </view>
    </view>
    
    <!-- 会员升级横幅 -->
    <view class="membership-banner" @click="goToVip">
      <image class="membership-banner-image"  src="/static/profileSvip.png" mode=""></image>
    </view>
    
    <!-- 功能菜单区域 -->
    <view class="menu-section">
      <view class="menu-item" @click="goToPersonalInfo">
        <view class="menu-icon personal-icon">
         <image class="menu-icon-img" src="/static/tag1.png" mode=""></image>
        </view>
        <text class="menu-text">个人信息</text>
        <view class="arrow">
			 <uni-icons type="right" color="#1B1E5F" size="20" ></uni-icons>
		</view>
      </view>
      
      <view class="menu-item" @click="goToSearchHistory">
        <view class="menu-icon search-history-icon">
          <image class="menu-icon-img" src="/static/tag2.png" mode=""></image>
        </view>
        <text class="menu-text">搜题记录</text>
        <view class="arrow">
			 <uni-icons type="right" color="#1B1E5F" size="20" ></uni-icons>
		</view>
      </view>
      
      <view class="menu-item" @click="goToGoldBeans('/pages/golden-bean-record/golden-bean-record')">
        <view class="menu-icon gold-beans-icon">
          <image class="menu-icon-img" src="/static/tag3.png" mode=""></image>
        </view>
        <text class="menu-text">金豆记录</text>
        <view class="arrow">
			 <uni-icons type="right" color="#1B1E5F" size="20" ></uni-icons>
		</view>
      </view>
      
      <view class="menu-item" @click="goToGoldBeans('/pages/cooperation/cooperation')">
        <view class="menu-icon cooperation-icon">
          <image class="menu-icon-img" src="/static/tag4.png" mode=""></image>
        </view>
        <text class="menu-text">合作加盟</text>
        <view class="arrow">
			 <uni-icons type="right" color="#1B1E5F" size="20" ></uni-icons>
		</view>
      </view>

      <!-- 微信小程序使用 button 打开客服 -->
      <button v-if="isWeixinMP" class="menu-item menu-button" open-type="contact">
        <view class="menu-icon service-icon">
          <image class="menu-icon-img" src="/static/tag5.png" mode=""></image>
        </view>
        <text class="menu-text">在线客服</text>
        <view class="arrow">
			 <uni-icons type="right" color="#1B1E5F" size="20" ></uni-icons>
		</view>
      </button>
      <!-- 其他平台跳转到在线客服页面 -->
      <view v-else class="menu-item" @click="goToGoldBeans('/pages/on-line/on-line')">
        <view class="menu-icon service-icon">
          <image class="menu-icon-img" src="/static/tag5.png" mode=""></image>
        </view>
        <text class="menu-text">在线客服</text>
        <view class="arrow">
			 <uni-icons type="right" color="#1B1E5F" size="20" ></uni-icons>
		</view>
      </view>

      <view class="menu-item" @click="goToAbout">
        <view class="menu-icon about-icon">
          <image class="menu-icon-img" src="/static/tag6.png" mode=""></image>
        </view>
        <text class="menu-text">关于我们</text>
        <view class="arrow">
			 <uni-icons type="right" color="#1B1E5F" size="20" ></uni-icons>
		</view>
      </view>
      
      <view class="menu-item" @click="goToPrivacy">
        <view class="menu-icon privacy-icon">
           <image class="menu-icon-img" src="/static/tag7.png" mode=""></image>
        </view>
        <text class="menu-text">隐私政策</text>
        <view class="arrow">
			 <uni-icons type="right" color="#1B1E5F" size="20" ></uni-icons>
		</view>
      </view>

      <!-- 退出登录菜单项，仅在已登录时显示 
      <view v-if="isUserLoggedIn" class="menu-item logout-menu-item" @click="logout">
        <view class="menu-icon logout-icon">
           <text class="logout-icon-text">⚠</text>
        </view>
        <text class="menu-text logout-text">退出登录</text>
        <view class="arrow">
			 <uni-icons type="right" color="#1B1E5F" size="20" ></uni-icons>
		</view>
      </view>-->
    </view>

    <!-- 登录弹窗组件 -->
    <LoginModal
      ref="loginModalRef"
      @close="onLoginModalClose"
      @skip="onLoginSkip"
      @login="onLoginSuccess"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { isLoggedIn, getCurrentUser, getDefaultUserInfo, navigateToLogin, clearUserLogin, fetchUserInfo } from '../../utils/user.js'
import { isWeixinMiniProgram } from '../../utils/platform.js'
import LoginModal from '@/components/LoginModal/LoginModal.vue'

// 响应式数据
const isUserLoggedIn = ref(false)
const userInfo = ref({})

// 登录弹窗引用
const loginModalRef = ref()

// 平台判断
const isWeixinMP = ref(isWeixinMiniProgram())

onMounted(() => {
  console.log('我的页面已加载')
  checkLoginStatus()
})

// 页面显示时重新检查登录状态
onShow(() => {
  console.log('profile页面显示，重新检查登录状态')
  // 添加延迟确保数据已经保存到服务器
  setTimeout(() => {
    checkLoginStatus()
  }, 500) // 增加延迟时间，确保服务器数据已更新
})

// 检查登录状态并更新用户信息
const checkLoginStatus = async () => {
  console.log("=== 开始检查登录状态 ===")
  const loginStatus = isLoggedIn()
  isUserLoggedIn.value = loginStatus

  console.log("检查登录状态:", loginStatus);

  if (isUserLoggedIn.value) {
    // 已登录，请求最新用户信息
    try {
      console.log("正在获取最新用户信息...")
      const userData = await fetchUserInfo()
      console.log("获取到的用户数据:", userData)
      updateUserInfo(userData)
      console.log("用户信息更新完成")
    } catch (error) {
      console.error("获取用户信息失败:", error);
      // 获取失败时使用本地存储的用户信息
      const currentUser = getCurrentUser()
      if (currentUser) {
        console.log("使用本地存储的用户信息:", currentUser)
        updateUserInfo(currentUser)
      } else {
        // 本地也没有用户信息，使用默认信息
        console.log("本地无用户信息，使用默认信息")
        userInfo.value = getDefaultUserInfo()
        isUserLoggedIn.value = false
      }
    }
  } else {
    // 未登录，使用默认信息
    console.log("未登录，使用默认信息");
    userInfo.value = getDefaultUserInfo()
  }
  console.log("=== 登录状态检查完成 ===")
}

// 头像加载成功回调
const onAvatarLoad = () => {
  console.log('头像加载成功:', userInfo.value.avatar)
}

// 头像加载失败回调
const onAvatarError = (e) => {
  console.error('头像加载失败:', e, userInfo.value.avatar)
  // 如果头像加载失败，使用默认头像
  userInfo.value.avatar = '/static/profile/avatar.jpg'
}

// 更新用户信息显示
const updateUserInfo = (userData) => {
  console.log('更新用户信息:', userData)

  // 处理头像URL，添加时间戳防止缓存
  let avatarUrl = userData.avatar || '/static/profile/avatar.jpg'

  // 特殊处理默认头像
  if(userData.avatar && userData.avatar == "https://devoss.igmdns.com/avatar/avatar.jpg"){
    avatarUrl = '/static/profile/avatar.jpg'
  } else if (userData.avatar && userData.avatar.startsWith('http')) {
    // 对于网络图片，添加时间戳防止缓存
    const timestamp = Date.now()
    avatarUrl = userData.avatar.includes('?')
      ? `${userData.avatar}&t=${timestamp}`
      : `${userData.avatar}?t=${timestamp}`
  }

  console.log('处理后的头像URL:', avatarUrl)

  userInfo.value = {
    userName: userData.nickname || '用户',
    userId: `ID: ${userData.userid || '未知'}`,
    signature: userData.signature || '这个人很懒，什么都没留下',
    avatar: avatarUrl,
    searchCount: userData.pkg_credit || 0,
    friendCount: userData.friend_count || 0,
    is_svip: userData.is_svip || 0
  }
}

// 处理头像点击事件
const handleAvatarClick = () => {
  // 检查登录状态
  const loginStatus = isLoggedIn()
  if (!loginStatus) {
    // 判断是否为微信小程序
    if (isWeixinMiniProgram()) {
      // 微信小程序显示登录弹窗
      showLoginModal()
    } else {
      // 其他平台跳转到登录页面
      navigateToLogin('/pages/profile/profile')
    }
    return
  }

  // 已登录，跳转到个人信息页面
  uni.navigateTo({
    url: '/pages/personal-info/personal-info',
    fail: (error) => {
      console.error('跳转个人信息页面失败:', error)
      uni.showToast({
        title: '跳转失败',
        icon: 'error'
      })
    }
  })
}

// 登录弹窗相关方法
const showLoginModal = () => {
  loginModalRef.value?.open()
}

const onLoginModalClose = () => {
  console.log('登录弹窗关闭')
}

const onLoginSkip = () => {
  uni.showToast({
    title: '暂不登录',
    icon: 'none',
    duration: 2000
  })
}

const onLoginSuccess = () => {
  // 弹框处理了登录逻辑 这里只处理登录完成逻辑
  console.log('登录成功')

  // 重新加载用户信息
  checkLoginStatus()

  // 提示用户登录成功
  uni.showToast({
    title: '登录成功',
    icon: 'success'
  })
}

const goBack = () => {
  uni.navigateBack()
}

const goToPersonalInfo = () => {
  uni.navigateTo({
    url: '/pages/personal-info/personal-info'
  })
}

const goToSearchHistory = () => {
  uni.navigateTo({
    url: '/pages/search-history/search-history',
    fail: (error) => {
      console.error('跳转搜题记录页面失败:', error)
      uni.showToast({
        title: '跳转失败',
        icon: 'error'
      })
    }
  })
}

const goToInviteFriendsRecord = () => {
  uni.navigateTo({
    url: '/pages/invite-friends-record/invite-friends-record',
    fail: (error) => {
      console.error('跳转邀请好友记录页面失败:', error)
      uni.showToast({
        title: '跳转失败',
        icon: 'error'
      })
    }
  })
}

const goToGoldBeans = (url) => {
  uni.navigateTo({
    url:url,
    fail: (error) => {
      console.error('跳转金豆记录页面失败:', error)
      uni.showToast({
        title: '跳转失败',
        icon: 'error'
      })
    }
  })
}

const goToCooperation = () => {
  uni.showToast({
    title: '合作加盟功能开发中',
    icon: 'none'
  })
}

const goToCustomerService = () => {
  uni.showToast({
    title: '在线客服功能开发中',
    icon: 'none'
  })
}

const goToAbout = () => {
  uni.navigateTo({
    url: '/pages/about-us/about-us'
  })
}

const goToPrivacy = () => {
  uni.navigateTo({
    url: '/pages/privacy-policy/privacy-policy'
  })
}

const goToVip = () => {
  uni.navigateTo({
    url: '/pages/vip/vip',
    fail: (error) => {
      console.error('跳转VIP页面失败:', error)
      uni.showToast({
        title: '跳转失败，请重试',
        icon: 'error'
      })
    }
  })
}

const logout = () => {
  if (!isUserLoggedIn.value) {
    uni.showToast({
      title: '您还未登录',
      icon: 'none'
    })
    return
  }

  uni.showModal({
    title: '确认退出',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        // 清除登录信息
        clearUserLogin()

        // 更新页面状态
        checkLoginStatus()

        uni.showToast({
          title: '已退出登录',
          icon: 'success'
        })
      }
    }
  })
}
</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  padding: 0;
  position: relative;
}

.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx;
  background: #E3F2FD;
}

.status-time {
  font-size: 32rpx;
  font-weight: 600;
  color: #000;
}

.status-icons {
  display: flex;
  gap: 16rpx;
}

.status-icon {
  font-size: 28rpx;
  color: #000;
}

/* 返回按钮 */
.back-button {
  position: absolute;
  top: 60rpx;
  left: 40rpx;
  z-index: 10;
}

.back-arrow {
  font-size: 48rpx;
  color: #333;
  font-weight: bold;
}

/* 用户信息区域 */
.user-info-section {
  display: flex;
  align-items: center;
  margin: 0;
  padding: 160rpx 40rpx 40rpx;
}

.user-avatar {
  width: 145rpx;
  height: 140rpx;
  overflow: hidden;
  margin-right: 30rpx;
  position: relative;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.user-avatar:active {
  transform: scale(0.95);
}
.user-avatar-kua{
	margin: 20rpx 0 0 20rpx;
	width: 115rpx;
	height: 115rpx;
	border:5rpx solid #fff;
	border-radius: 50%;
}
.avatar-img {
  width: 112rpx;
  height: 112rpx;
  border-radius: 50%;
}

.vip-crown {
  position: absolute;
  top: 0rpx;
  right: 0rpx;
width: 52rpx;
height: 52rpx;
}
.menu-icon-img{
	width: 40rpx;
	height: 40rpx;
}
.crown-text {
  font-size: 24rpx;
}

.user-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.name-row {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.user-name {
font-weight: 500;
font-size: 36rpx;
color: #000000;
line-height: 50rpx;
text-align: left;
}

.user-id {
  font-size: 20rpx;
  color: #FF6B35;
  font-weight: 300;
 text-align: left;
 background-color: #FEF9F1;
 padding: 0 10rpx;
border-radius: 22rpx 22rpx 22rpx 22rpx;
}

.user-bio {
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
  font-weight: 300;
}

/* 数据统计区域 */
.stats-section {
  display: flex;
  margin: 0;
  padding: 0 40rpx 20rpx;
  gap: 20rpx;
}

.stat-card {
  flex: 1;
  background: white;
  border-radius: 16rpx;
  padding: 30rpx 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  gap: 8rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}
.stat-label{
    display: flex;
    flex-direction: column;
}
.stat-icon {
  width: 65rpx;
  height: 65rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8rpx;
}

.icon-text {
  width: 65rpx;
  height: 65rpx;
}

.stat-number {
  font-size: 40rpx;
  font-weight: 400;
  color: #333;
  text-align: left;
  line-height: 56rpx;
  margin-bottom: 4rpx;
}

.stat-label {
  font-size: 24rpx;
   font-weight: 500;
  color: #666;
}

/* 会员升级横幅 */
.membership-banner {
  margin: 0 40rpx 20rpx;
  height: 146rpx;
}

.membership-banner-image{
	width: 100%;
	height: 146rpx;
	border-radius: 12rpx;
}
.banner-content {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.banner-icon {
  width: 60rpx;
  height: 60rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.gift-icon {
  font-size: 32rpx;
}

.banner-text {
  flex: 1;
}

.banner-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 600;
}

.upgrade-btn {
  background: #FF4757;
  color: white;
  border: none;
  border-radius: 20rpx;
  padding: 5rpx 24rpx;
  display: flex;
  align-items: center;
}

.upgrade-text {
  font-size: 28rpx;
  font-weight: 600;
}

.upgrade-arrow {
  font-size: 24rpx;
  font-weight: bold;
}

/* 功能菜单区域 */
.menu-section {
  background: white;
  margin: 0 40rpx;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 32rpx 40rpx;
  transition: background-color 0.3s ease;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-item:active {
  background-color: #F8F9FA;
}

/* button 组件样式重置 */
.menu-button {
  background: transparent;
  border: none;
  padding: 32rpx 40rpx;
  margin: 0;
  line-height: normal;
  text-align: left;
  width: 100%;
}

.menu-button::after {
  border: none;
}

.menu-icon {
  width: 50rpx;
  height: 50rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
}

.personal-icon {
  background: #E3F2FD;
}

.search-history-icon {
  background: #E8F5E8;
}

.gold-beans-icon {
  background: #FFF3E0;
}

.cooperation-icon {
  background: #F3E5F5;
}

.service-icon {
  background: #E0F2F1;
}

.about-icon {
  background: #FFF8E1;
}

.privacy-icon {
  background: #F1F8E9;
}

.logout-icon {
  background: #FFEBEE;
}

.logout-icon-text {
  font-size: 24rpx;
  color: #F44336;
}

.logout-menu-item {
  border-top: 1rpx solid #F5F5F5;
}

.logout-text {
  color: #F44336;
}

.icon-text {
  font-size: 24rpx;
}

.menu-text {
  flex: 1;
  font-size: 32rpx;
  color: #333;
  font-weight: 400;
}

.arrow {
  font-size: 32rpx;
  color: #CCC;
  font-weight: bold;
}

/* 退出登录按钮 */
.logout-section {
  padding: 40rpx;
  background: white;
  margin-top: 20rpx;
}

.logout-btn {
  width: 100%;
  height: 80rpx;
  background: #FF4757;
  color: white;
  border: none;
  border-radius: 20rpx;
  font-size: 32rpx;
  font-weight: 500;
  transition: all 0.3s ease;
}

.logout-btn:active {
  background: #E53E3E;
}
</style>
